package com.freshman_registration.controller;

import com.freshman_registration.pojo.PaymentItem;
import com.freshman_registration.pojo.PaymentRecord;
import com.freshman_registration.service.PaymentService;
import com.freshman_registration.util.Result;
import com.github.pagehelper.Page;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@RestController
@RequestMapping("/api/payment")
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;
    // =================== 学生端 ===================
    /**
     * 学生端 - 查看可缴费项目
     */
    @GetMapping("/student/activeItems")
    public Result<?> getActivePaymentItems(@RequestParam String studentId) {
        return paymentService.getActivePaymentItems(studentId);
    }

    /**
     * 学生端 - 查看个人缴费记录
     */
    @GetMapping("/student/records")
    public Result<?> getMyPaymentRecords(@RequestParam String studentId) {
        return paymentService.getMyPaymentRecords(studentId);
    }

    /**
     * 学生端 - 缴纳费用
     */
    @PostMapping("/student/pay")
    public Result<?> payForItem(@RequestParam Integer itemId, @RequestParam String studentId) {
        return paymentService.payForItem(itemId, studentId);
    }


    // =================== 管理员端 ===================



    /**
     * 管理员端 - 发布缴费项目
     */
    @PostMapping("/admin/addItem")

    public Result<?> addPaymentItem(@RequestBody PaymentItem paymentItem) {
        return paymentService.addPaymentItem(paymentItem);
    }

    /**
     * 管理员端 - 查看所有缴费项目
     */
    @GetMapping("/admin/allItems")
    public Result<?> getAllPaymentItems(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        return paymentService.getAllPaymentItems(pageNum, pageSize);
    }
    /*
     * 管理员端-按照项目名称模糊查询缴费项目
     */
    @GetMapping("/admin/searchItems")
    public Result<?> searchPaymentItems(
            @RequestParam(required = false) String itemName,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status) {
        // 调用服务层方法，支持模糊查询和分页
        return paymentService.searchItemsByName(itemName, pageNum, pageSize, status);
    }


    /**
     * 管理员端 - 获取所有缴费记录
     * 管理员查询所有学生缴费记录
     *  支持按学号、缴费状态、截止日期范围筛选
     */

    @GetMapping("/admin/records")
    public Result<Page<PaymentRecord>> getAllRecordsByPage(
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) Integer itemId,
            @RequestParam(required = false) String paymentStatus,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String itemName,
            @RequestParam(required = false) String itemType

    ) {

        Page<PaymentRecord> page = paymentService.getAllPaymentRecordsByPage(
                pageNum, pageSize, studentId, itemId, paymentStatus, startDate, endDate,itemName, itemType);

        return Result.success(page);
    }



    // 用于日期格式化
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 管理员端 - 导出缴费记录（Hutool 实现）
     */
    @GetMapping("/admin/exportRecords")
    public void exportPaymentRecords(
            @RequestParam(required = false) Integer itemId,
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) String paymentStatus,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String itemName,
            @RequestParam(required = false) String itemType,
            HttpServletResponse response) throws IOException {

        paymentService.exportPaymentRecords(
                itemId, studentId, paymentStatus,
                startDate, endDate, itemName, itemType,
                response);
    }



    /*
     * 管理员端修改缴费项目
     */
    @PutMapping("/admin/updateItem")
    public Result<?> updatePaymentItem(@RequestBody PaymentItem item) {
        return paymentService.updatePaymentItem(item);
    }

    /*
     * 管理员端删除缴费项目
     */
    @DeleteMapping("/admin/deleteItem")
    public Result<?> deletePaymentItem(@RequestParam Integer itemId) {
        return paymentService.deletePaymentItem(itemId);
    }








    //学生端通过学号和项目id查询
    @GetMapping("/student/queryrecord")
    public Result<?> queryRecord(@RequestParam String studentId, @RequestParam Integer itemId) {
        PaymentRecord record = paymentService.selectByStudentIdAndItemId(studentId, itemId);
        if (record != null) {
            return Result.success("查询成功", record.getPaymentStatus());
        } else {
            return Result.fail("查询失败");
        }
    }
    /**
     * 同步支付状态（批量更新）
     * 接收前端传递的学生ID、项目ID列表和支付状态，更新数据库中对应记录
     */
    /**
     * 同步支付状态接口（批量更新）
     */
    @PostMapping("/syncStatus")
    public Result<?> syncPaymentStatus(
            @RequestParam String studentId,
            @RequestParam List<Integer> itemIds,
            @RequestParam String paymentStatus) {

        log.info("开始批量更新支付状态 | studentId: {}, itemIds: {}, paymentStatus: {}",
                studentId, itemIds, paymentStatus);
        // 参数校验
        if (studentId == null || studentId.isEmpty()) {
            return Result.fail("学生ID不能为空");
        }
        if (itemIds == null || itemIds.isEmpty()) {
            return Result.fail("项目ID列表不能为空");
        }
        if (paymentStatus == null || paymentStatus.isEmpty()) {
            return Result.fail("支付状态不能为空");
        }

        try {
            // 调用服务层更新状态
            int updatedRows = paymentService.batchUpdateStatus(studentId, itemIds, paymentStatus);
            if (updatedRows > 0) {
                return Result.success("同步成功", updatedRows);
            } else {
                return Result.fail("未找到匹配的缴费记录");
            }
        } catch (Exception e) {
            return Result.fail("同步失败：" + e.getMessage());
        }
    }

}
